import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { TransferDrawCardsToDiscardCardsMessageData } from "../types/MessageData";
import { Card } from "../../../types/Card";

export const transferDrawCardsToDiscardCardsHandler = ({ user, payload }: { client: WebSocket; user: User; payload: TransferDrawCardsToDiscardCardsMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	if (room && player) {
		const selectedCards: Card[] = [];
		payload.cardIds.forEach((cardId) => {
			const handCardsIndex = room.drawCards.findIndex((v) => v.cardId === cardId);
			if (handCardsIndex !== -1) {
				selectedCards.push(room.drawCards[handCardsIndex]);
				room.drawCards.splice(handCardsIndex, 1);
			}
		});
		switch (payload.position) {
			case "top":
				room.discardCards.unshift(...selectedCards);
				break;
			case "bottom":
				room.discardCards.push(...selectedCards);
				break;
			case "random":
				for (let i = 0; i < selectedCards.length; i++) {
					const index = Math.floor(Math.random() * (room.discardCards.length + 1));
					room.discardCards.splice(index, 0, selectedCards[i]);
				}
				break;
		}
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "transferredDrawCardsToDiscardCards", payload: { roomId: room.roomId, userId: user.userId, cards: selectedCards, position: payload.position } })));
		const log = { userId: user.userId, username: user.username, log: "将摸牌堆的" + selectedCards.length + "张牌" + (payload.position == "top" ? "置顶" : payload.position == "bottom" ? "置底" : "随机置于") + "了弃牌堆。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
